package com.chuan.thinkingjava.sync;

public class TestSync {

    Object obj = new Object();

    void exec1() throws InterruptedException {
        synchronized (obj) {
            for (int i = 0; i < 5; i++) {
                Thread.sleep(100);//省略try_catch
                System.out.println("exec1-->" + Thread.currentThread().getName() + "-->" + i);
            }
        }
    }

     void exec2() throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            Thread.sleep(100);//省略try_catch
            System.out.println("exec2-->" + Thread.currentThread().getName() + "-->" + i);
        }
    }

    public static void main(String[] args) {
        //先将对象实例化,两个线程用的是一个对象
        final TestSync syncDemo1 = new TestSync();
        final TestSync syncDemo2 = new TestSync();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    syncDemo1.exec1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "thread1").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    syncDemo2.exec1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "thread2").start();
    }
}
